package com.ccp.dev.workflow.service;

import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.Dom4jUtil;
import com.ccp.dev.core.util.XmlBeanUtil;
import com.ccp.dev.form.xml.util.XmlUtil;
import com.ccp.dev.workflow.dao.ConditionScriptDao;
import com.ccp.dev.workflow.model.ConditionScript;
import com.ccp.dev.workflow.xml.ConditionScriptXml;
import com.ccp.dev.workflow.xml.ConditionScriptXmlList;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassDescribe:系统条件脚本 Service类
 * @author :jiayueqiao
 * Date: 2019-07-09
 * Since:1
 */
@Service
public class ConditionScriptService extends BaseService<ConditionScript> {

    @Resource
    private ConditionScriptDao conditionScriptDao;

    /**
     * 获取对应类名的所有方法
     * @param name 类名称
     * @return JSONArray
     * @throws Exception 异常
     */
    public JSONArray getMethodsByName(String name) throws Exception {
        JSONArray ary = new JSONArray();
        Class<?> t = Class.forName(name);
        Method[] methods = t.getDeclaredMethods();
        for(Method method : methods){
            String returnType = method.getReturnType().getCanonicalName();
            //只要返回值为boolean的方法
            if(!"boolean".equals(returnType)&&!"java.lang.Boolean".equals(returnType)){ continue;}
            Integer modifirer = method.getModifiers();
            //只要public方法
            if(modifirer!=1){  continue; }
            JSONObject jobMethod = new JSONObject();
            JSONArray jaryPara = new JSONArray();
            Class<?>[] paraArr = method.getParameterTypes();
            for(int i=0;i<paraArr.length;i++){
                Class<?> para = paraArr[i];
                String paraName = "arg" + i;
                String paraType = para.getCanonicalName();
                jaryPara.add(new JSONObject().accumulate("paraName", paraName)
                        .accumulate("paraType", paraType)
                        .accumulate("paraDesc", ""));
            }
            jobMethod.accumulate("returnType", returnType)
                    .accumulate("methodName", method.getName())
                    .accumulate("para", jaryPara);
            ary.add(jobMethod);
        }
        return ary;
    }

    /**
     * 验证脚本是否有效
     * @return String
     */
    public String validScriptIsEnable() {
        String message;
        Boolean hasUnEnable = false;
        List<ConditionScript> list = conditionScriptDao.queryList(null);
        if(BeanUtils.isEmpty(list)){
            message = "script.invalid";
        }else{
            Class<?> t;
            for(ConditionScript conditionScript : list){
                try{
                    t = Class.forName(conditionScript.getClassName());
                    String paraStr = conditionScript.getArgument();
                    JSONArray jarry = JSONArray.fromObject(paraStr);
                    Integer size = jarry.size();
                    Class<?>[] paras = new Class<?>[size];
                    for(int i=0;i<size;i++){
                        JSONObject jobject = jarry.getJSONObject(i);
                        paras[i] = Class.forName(jobject.getString("paraType"));
                    }
                    Method method = t.getMethod(conditionScript.getMethodName(), paras);
                    String returnTypeStr = method.getReturnType().getCanonicalName();
                    if(!"boolean".equals(returnTypeStr)&&!"java.lang.Boolean".equals(returnTypeStr))
                    {  throw new Exception("返回值不是Boolean类型"); }
                    if(method.getModifiers()!=Modifier.PUBLIC)
                    {   throw new Exception("方法不是public类型"); }
                }
                catch(Exception ex){
                    hasUnEnable = true;
                    conditionScript.setEnable(1);
                    conditionScriptDao.update(conditionScript);
                }
            }
            if(hasUnEnable) {
                message = "script.valid.failure";
            }else {
                message = "script.valid.success";
            }
        }
        return message;
    }

    /**
     * 获取所有 有效的条件脚本
     * @return list
     */
    public List<ConditionScript> queryConditionScript() {
        return conditionScriptDao.queryConditionScript();
    }
    /**
     * 导出全部条件脚本
     * @param conditionScripts 脚本
     * @return xml
     * @throws Exception 异常
     */
    public String exportXml(List<ConditionScript> conditionScripts)throws Exception {
        ConditionScriptXmlList conditionScriptXmlList = new ConditionScriptXmlList();
        List<ConditionScriptXml> list = new ArrayList<>();
        for (ConditionScript conditionScript : conditionScripts) {

            ConditionScriptXml conditionScriptXml = this.exportConditionScriptXml(conditionScript);
            list.add(conditionScriptXml);
        }
        conditionScriptXmlList.setConditionScriptXmlList(list);
        return XmlBeanUtil.marshall(conditionScriptXmlList,ConditionScriptXmlList.class);
    }
    /**
     * 导出条件脚本XML
     * @param ids 条件脚本id
     * @return xml
     * @throws Exception 异常
     */
    public String exportXml(String[] ids) throws Exception {
        ConditionScriptXmlList conditionScriptXmlList = new ConditionScriptXmlList();
        List<ConditionScriptXml> list = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            ConditionScript conditionScript = conditionScriptDao.getById(ids[i]);
            ConditionScriptXml conditionScriptXml = this.exportConditionScriptXml(conditionScript);
            list.add(conditionScriptXml);
        }
        conditionScriptXmlList.setConditionScriptXmlList(list);
        return XmlBeanUtil.marshall(conditionScriptXmlList,ConditionScriptXmlList.class);
    }

    /**
     * 导出表的信息
     * @param conditionScript 条件脚本
     * @return ConditionScriptXml
     */
    private ConditionScriptXml exportConditionScriptXml(ConditionScript conditionScript) {
        ConditionScriptXml conditionScriptXml=new ConditionScriptXml();
        String id=conditionScript.getId();
        if(BeanUtils.isNotIncZeroEmpty(id)){
            //导出条件脚本
            conditionScriptXml.setConditionScript(conditionScript);
        }
        return conditionScriptXml;
    }

    /**
     * 导入条件脚本XML
     * @param inputStream 输入流
     * @throws Exception 异常
     */
    @Transactional(rollbackFor = Exception.class)
    public void importXml(InputStream inputStream) throws Exception {
        Document doc = Dom4jUtil.loadXml(inputStream);
        Element root = doc.getRootElement();
        // 验证格式是否正确
        XmlUtil.checkXmlFormat(root, "system", "conditionScripts");

        String xmlStr = root.asXML();
        ConditionScriptXmlList conditionScriptXmlList = (ConditionScriptXmlList) XmlBeanUtil.unmarshall(xmlStr, ConditionScriptXmlList.class);

        List<ConditionScriptXml> list = conditionScriptXmlList.getConditionScriptXmlList();

        for (ConditionScriptXml conditionScriptXml : list) {
            // 导入表，并解析相关信息
            this.importConditionScriptXml(conditionScriptXml);
        }
    }

    /**
     * 导入时生成条件脚本
     * @param conditionScriptXml conditionScriptXml
     * @throws Exception 异常
     */
    private void importConditionScriptXml(ConditionScriptXml conditionScriptXml)throws Exception {
        String conditionScriptId = UUIDUtils.getUUIDFor32();
        ConditionScript conditionScript = conditionScriptXml.getConditionScript();
        if (BeanUtils.isEmpty(conditionScript)) {
            throw new Exception();
        }
        conditionScript.setId(conditionScriptId);
        conditionScriptDao.add(conditionScript);
    }
}
